package com.emm.yixun.website.controller.customer;

//框架包
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.IdentityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.anotations.AvoidDuplicateSubmission;
import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.anotations.UserOperateLog;
import com.emm.yixun.common.enums.FunctionTypeEnum;
import com.emm.yixun.common.enums.ModelTypeEnum;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.SubscribeInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BaseCodeTypeEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessFlagEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.FamilyMemberServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.ImageServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.ao.DataService.OaDataService;
import com.emm.yixun.website.service.customer.SubscribeService;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.service.marketing.HaveReceiveRefundService;
import com.emm.yixun.website.utils.ExcelUtil;
import com.emm.yixun.website.utils.TokenProcessor;
import com.emm.yixun.website.vo.common.ExtResultVo;

@Controller
@RequestMapping("/customer/subscribe/")
public class SubscribeController extends BaseController<Subscribe> {

	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;
	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private FamilyMemberServiceFacade familyMemberServiceFacade;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private ImageServiceFacade imageServiceFacade;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private OaDataService oaDataService;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/customer/subscribe/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "toAdd")
	@MerchantResourcesConfig(resourcesCode = "menu_0005_0004_0014")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toAdd(ModelMap map, String roomId,String customerId, String payDepositId, HttpServletRequest request,
			HttpServletResponse resp, String returnUrl, String isChooseCustomer) {

		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:add")) {
			Boolean showChooseCustomer = Boolean.FALSE;
			// 查询菜单按钮权限
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response2 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response2.isSuccess()) {
				payDepositOff = response2.getEntity();
			}
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("userId", user.getId());
			String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(user.getMerchantId());
			bcvDto.setProjectId(Long.parseLong(request.getParameter("projectId")));
			bcvDto.setTypeName(typeName);
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
			bcvDto.setOrders("t.sort*1");
			JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));

			map.put("payDeposit", new PayDeposit());
			if (StringUtils.isNotBlank(payDepositId)) {
				Response<PayDeposit> response = payDepositServiceFacade.findById(Long.valueOf(payDepositId));
				if (response.isSuccess() && null != response.getEntity()) {
					PayDeposit payDeposit = response.getEntity();
					/*
					 * if (null != payDeposit.getCustomerId()) customerId =
					 * String.valueOf(payDeposit.getCustomerId()); if (null !=
					 * payDeposit.getRoomId()) roomId = String.valueOf(payDeposit.getRoomId());
					 */
					HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
					entity.setDocType("0");
					entity.setReceivablesType("0");
					entity.setRelationId(Long.valueOf(payDepositId));
					entity.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_1.getNo());
					Double amount = haveReceiveRefundService.getRealAmount(entity);
					payDeposit.setPayDepositAmount(new BigDecimal(amount));
					map.put("payDeposit", payDeposit);
				}

			}

			if (!com.alibaba.druid.util.StringUtils.isEmpty(customerId)) {
				map.put("customerId", customerId);
				Response<Customer> customerResponse = customerServiceFacade.findById(Long.valueOf(customerId));
				if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
					map.put("customerProjectId", customerResponse.getEntity().getProjectId());
				}
			}

			if (!com.alibaba.druid.util.StringUtils.isEmpty(roomId)) {
				map.put("roomId", roomId);
			}

			map.put("documentType", dtArray.toJSONString());

			// map.put("payDepositId",
			// StringUtils.isBlank(payDepositId)?"":payDepositId);
			map.put("menu", request.getParameter("menu"));
			if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
				map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			}

			map.put("projectId", request.getParameter("projectId"));
			map.put("payDepositOff", payDepositOff);
			if (StringUtils.isNotBlank(isChooseCustomer))
				showChooseCustomer = Boolean.TRUE;
			map.put("showChooseCustomer", showChooseCustomer);

			return "/customer/subscribe/add";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	/**
	 * 绿城项目客户信息完善必须满足意向等级为A的才可以认购，不满足跳转客户编辑页面
	 * 
	 * @param map
	 * @param roomId
	 * @param customerId
	 * @param payDepositId
	 * @param request
	 * @param returnUrl
	 * @param isChooseCustomer
	 * @return
	 */
	@RequestMapping(value = "toAddLC")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toAddLC(ModelMap map, String roomId, String customerId, String payDepositId,
			HttpServletRequest request, String returnUrl, String isChooseCustomer) {

		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:add")) {
			Boolean showChooseCustomer = Boolean.FALSE;
			// 查询菜单按钮权限
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response2 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response2.isSuccess()) {
				payDepositOff = response2.getEntity();
			}
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("userId", user.getId());
			String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(user.getMerchantId());
			bcvDto.setProjectId(Long.parseLong(request.getParameter("projectId")));
			bcvDto.setTypeName(typeName);
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
			bcvDto.setOrders("t.sort*1");
			JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
			map.put("payDeposit", new PayDeposit());
			if (StringUtils.isNotBlank(payDepositId)) {
				Response<PayDeposit> response = payDepositServiceFacade.findById(Long.valueOf(payDepositId));
				if (response.isSuccess() && null != response.getEntity()) {
					PayDeposit payDeposit = response.getEntity();
					/*
					 * if (null != payDeposit.getCustomerId()) customerId =
					 * String.valueOf(payDeposit.getCustomerId()); if (null !=
					 * payDeposit.getRoomId()) roomId = String.valueOf(payDeposit.getRoomId());
					 */
					HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
					entity.setDocType("0");
					entity.setReceivablesType("0");
					entity.setRelationId(Long.valueOf(payDepositId));
					entity.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_1.getNo());
					Double amount = haveReceiveRefundService.getRealAmount(entity);
					payDeposit.setPayDepositAmount(new BigDecimal(amount));
					map.put("payDeposit", payDeposit);
				}

			}

			if (!com.alibaba.druid.util.StringUtils.isEmpty(customerId)) {
				map.put("customerId", customerId);
				Response<Customer> customerResponse = customerServiceFacade.findById(Long.valueOf(customerId));
				if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
					map.put("customerProjectId", customerResponse.getEntity().getProjectId());
				}
			}

			if (!com.alibaba.druid.util.StringUtils.isEmpty(roomId)) {
				map.put("roomId", roomId);
			}

			map.put("documentType", dtArray.toJSONString());

			map.put("menu", request.getParameter("menu"));
			if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
				map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "=").replace("*", "&"));
			}
			map.put("url", request.getServletPath() + "?" + request.getQueryString());

			map.put("projectId", request.getParameter("projectId"));
			map.put("payDepositOff", payDepositOff);
			if (StringUtils.isNotBlank(isChooseCustomer))
				showChooseCustomer = Boolean.TRUE;
			map.put("showChooseCustomer", showChooseCustomer);

			return "/customer/subscribe/addLC";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "toView")
	public String toView(ModelMap map, Long id, String procInstId, String processFlag, HttpServletRequest request,
			String returnUrl) {
		/* if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){ */
		// 查询菜单按钮权限

		User user = ShiroUtil.getCurrentUser();
		// 认筹开关,默认未关闭(false) ,true已关闭
		boolean payDepositOff = false;
		Response<Boolean> response4 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
		if (response4.isSuccess()) {
			payDepositOff = response4.getEntity();
		}
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		Response<SubscribeInfo> response = subscribeServiceFacade.findByIdInfo(id);

		if (response.isSuccess()) {

			SubscribeInfo subscribe = response.getEntity();
			map.put("oldSubId", subscribe.getOldId());
			if (subscribe.getDiscountApproval().equals("1")) {
				// 折扣审批编号 认购
				BusinessAbnormaDto bus = new BusinessAbnormaDto();
				bus.setBusinessId(subscribe.getId());
				bus.setBusinessType("0");
				ResponseList<BusinessAbnorma> responseListBus = businessAbnormaServiceFacade.findByDto(bus);
				if (responseListBus.isSuccess() && responseListBus.getEntity() != null
						&& responseListBus.getEntity().size() > 0) {
					map.put("busProcInstId", responseListBus.getEntity().get(0).getProcInstId());
					map.put("busAutoStatus", responseListBus.getEntity().get(0).getAuditStatus());
				}

			}
			subscribe.setReceivedPayAmount(haveAmountById(id));
			if (subscribe.getConversionSignDate() != null) {
				Date newConversionDate = com.emm.yixun.common.utils.DateUtils.addDay(subscribe.getConversionSignDate(),
						1);
				if (new Date().getTime() > newConversionDate.getTime()) {
					map.put("yanqiStatus", "0");
				} else {
					map.put("yanqiStatus", "1");
				}
			} else {
				map.put("yanqiStatus", "0");
			}
			map.put("procInstId", StringUtils.isBlank(procInstId) ? subscribe.getProcInstId() : procInstId);
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setReceivablesType("1");// 认购
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			haveReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_5.getNo());
			// haveReceiveRefundDto.setStatus("0");// 已结清
			ResponseList<HaveReceiveRefund> response3 = haveReceiveRefundServiceFacade.findByDto(haveReceiveRefundDto);
			if (response3.isSuccess()) {
				List<HaveReceiveRefund> haveReceiveRefunds = response3.getEntity();
				if (haveReceiveRefunds != null && haveReceiveRefunds.size() != 0) {
					BigDecimal total = new BigDecimal("0.00");
					for (HaveReceiveRefund refund : haveReceiveRefunds) {
						if (!refund.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
							map.put("amountDetail", "1");
							total = total.add(refund.getRealAmount());
						}
					}
					if (total.compareTo(subscribe.getDepositReceivable()) == 0) {
						map.put("shouStatus", "1");
					} else {
						map.put("shouStatus", "0");
					}
				} else {
					if (subscribe.getDepositReceivable().compareTo(new BigDecimal("0")) == 0
							|| subscribe.getDepositReceivable() == null) {
						map.put("shouStatus", "1");
					} else {
						map.put("shouStatus", "0");
					}

				}
			} else {
				map.put("shouStatus", "0");
			}
			Response<ProjectRoom> response2 = projectRoomServiceFacade.findById(subscribe.getRoomId());
			if (response2.isSuccess()) {
				ProjectRoom projectRoom = response2.getEntity();
				map.put("roomStatus", projectRoom.getRoomStatus());
			}
			map.put("auditStatus", subscribe.getAuditStatus());
			if (subscribe.getBusinessStatus().equals("5")) {
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
				businessAbnormaDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					map.put("businessAbnormaId", businessAbnormas.getEntity().get(0).getId());
					map.put("huanStatus", "1");
				} else {
					map.put("huanStatus", "0");
				}

			} else if (!subscribe.getBusinessStatus().equals("3")) {
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
				// businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					BusinessAbnorma abnorma = businessAbnormas.getEntity().get(0);
					if (abnorma.getAuditStatus().equals("1")) {// 待提交隐藏
						map.put("huanStatus", "1");
					} else if (abnorma.getAuditStatus().equals("2")) {// 已退回显示
						map.put("huanStatus", "0");
					}
					map.put("businessStatus", subscribe.getBusinessStatus());
				} else {
					businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					ResponseList<BusinessAbnorma> businessAbnormas2 = businessAbnormaServiceFacade
							.findByDto(businessAbnormaDto);
					if (businessAbnormas2.isSuccess() && businessAbnormas2.getEntity() != null
							&& businessAbnormas2.getEntity().size() != 0) {
						map.put("businessAbnormaId", businessAbnormas2.getEntity().get(0).getId());
						map.put("huanStatus", "1");
						map.put("businessStatus", "5");
					} else {
						map.put("huanStatus", "0");
						map.put("businessStatus", subscribe.getBusinessStatus());
					}
				}
			} else {// 已通过隐藏
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
				businessAbnormaDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					map.put("businessAbnormaId", businessAbnormas.getEntity().get(0).getId());
					map.put("huanStatus", "1");
				} else {
					map.put("huanStatus", "0");
				}
				map.put("businessStatus", subscribe.getBusinessStatus());
			}
			String subscribeStr = JSON.toJSONString(oaDataService.getsubscribeRecord(id));
			JSONObject object = JSONObject.parseObject(subscribeStr);
			subscribeStr = JSON.toJSONString(object);
			map.put("subscribeRecord", subscribeStr);
			map.put("businessStatus", subscribe.getBusinessStatus());

			JSONObject estateRecord = oaDataService.getEstateRecord(subscribe.getRoomId());
			estateRecord.put("calculateArea", subscribe.getCalculateArea());
			estateRecord.put("unitPrice", subscribe.getConversionPrice());
			estateRecord.put("totalPrice", subscribe.getLumpsumPrice());
			map.put("estateRecord", estateRecord.toJSONString());

			JSONObject customerRecord = oaDataService.getCustomerRecord(subscribe.getCustomerId());
			map.put("customerRecord", customerRecord.toJSONString());
			// User user =
			// userServiceFacade.findById(subscribe.getAgentId()).getEntity();
			map.put("userName", subscribe.getUserName());
		}
		map.put("documentType", dtArray.toJSONString());
		map.put("processFlag", processFlag != null ? processFlag : "false");
		map.put("subscribeId", id);
		map.put("permitBtn", getPermissionBtnArray());
		map.put("menu", request.getParameter("menu"));
		map.put("payDepositOff", payDepositOff);
		map.put("back", request.getParameter("back"));
		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			map.put("returnBackParam", returnUrl);
		}

		return "/customer/subscribe/view";
	}

	public BigDecimal haveAmountById(Long subId) {
		Response<Subscribe> subscribe = subscribeServiceFacade.findById(subId);
		if (subscribe.isSuccess() && subscribe.getEntity().getPayDepositId() != null) {
			NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
			needReceiveRefundDto.setBusinessType(BusinessTypeEnum.DEPOSIT.getNo());// 认购
			needReceiveRefundDto.setRelationId(subscribe.getEntity().getPayDepositId());
			ResponseList<NeedReceiveRefund> response = needReceiveRefundServiceFacade.findByDto(needReceiveRefundDto);
			if (response.isSuccess() && response.getEntity() != null) {
				NeedReceiveRefund reFund = response.getEntity().get(0);
				Response<BigDecimal> haveResp = haveReceiveRefundServiceFacade.findHaveAmount(reFund.getId());
				return haveResp.getEntity();
			} else {
				return new BigDecimal("0");
			}
		} else {
			return new BigDecimal("0");
		}
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_4, modelName = ModelTypeEnum.MODELTYPE_2, roomKey = "roomId")
	@AvoidDuplicateSubmission(needRemoveToken = true)
	public AjaxRes add(String params, Boolean startProcess, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		// 操作失败时,重新刷新提交Token
		String newToken = TokenProcessor.getInstance().generateToken(request);
		request.getSession(false).setAttribute("token", newToken);
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:add"))) {
			try {
				SubscribeDto paramsSubscribeDto = JSONObject.parseObject(params, SubscribeDto.class);
				Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade
						.findById(paramsSubscribeDto.getRoomId());
				Long projectId = projectRoomResponse.getEntity().getProjectId();
				if (null == projectId) {
					ar.setFailMsg("项目不存在!");
					ar.setObj(newToken);
					return ar;
				}
				// 是否需要发起折扣审批
				// 绿城有认购折扣、丰策不需要
				boolean needSubDiscountFlow = subDiscountFlowCheck(user);

				String subscribeStartProcessKey = "";
				String subscribeDiscountStartProcessKey = "";
				// 保存功能,不发起流程,无需验证是否有流程相关配置
				if (startProcess) {
					// 动态获取认购审批流程KEY
					subscribeStartProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
							ProcessTypeEnums.PROCESS_KEY_5);
					if (StringUtils.isEmpty(subscribeStartProcessKey)) {
						ar.setFailMsg("项目未设置认购审批流程,请去项目流程菜单配置！");
						ar.setObj(newToken);
						return ar;
					}
					// 检查流程节点是否已设置人员
					boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
							subscribeStartProcessKey);
					if (!isSeting) {
						ar.setFailMsg("认购审批流程节点人员未设置");
						ar.setObj(newToken);
						return ar;
					}

					// 动态获取认购折扣审批流程KEY
					if (needSubDiscountFlow) {
						subscribeDiscountStartProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(),
								projectId, ProcessTypeEnums.PROCESS_KEY_17);
						if (StringUtils.isEmpty(subscribeDiscountStartProcessKey)) {
							ar.setFailMsg("项目未设置认购折扣审批流程,请去项目流程菜单配置！");
							ar.setObj(newToken);
							return ar;
						}

						isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
								subscribeDiscountStartProcessKey);
						if (!isSeting) {
							ar.setFailMsg("认购折扣审批流程节点人员未设置");
							ar.setObj(newToken);
							return ar;
						}
					}
				}

				String resMsg = "认购成功";
				Response<SubscribeDto> response = subscribeServiceFacade.addSubscribe(params, user, null);
				if (response.isSuccess()) {
					String pid = null;
					SubscribeDto subscribeDto = response.getEntity();
					if (startProcess) {
						Map<String, Object> variables = new HashMap<String, Object>();
						identityService.setAuthenticatedUserId(user.getUserAccount());
						String discountApproval = subscribeDto.getDiscountApproval();
						String processKey = "";
						if ((discountApproval != null && discountApproval.equals("0")) || !needSubDiscountFlow) {
							// 不需要折扣审批
							processKey = subscribeStartProcessKey;
							pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
									processKey, subscribeDto.getId().toString(), variables);
						} else if (discountApproval != null && discountApproval.equals("1")) {
							// 需要折扣审批
							processKey = subscribeDiscountStartProcessKey;
							pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
									processKey, subscribeDto.getId().toString(), variables);
							// 更新销控业务异常表
							BusinessAbnormaDto queryDto = new BusinessAbnormaDto();
							queryDto.setBusinessId(subscribeDto.getId());
							queryDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_0.getNo());
							queryDto.setOrders(" t.id desc ");
							ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade
									.findByDto(queryDto);
							if (null != responseList && null != responseList.getEntity()
									&& responseList.getEntity().size() > 0) {
								BusinessAbnorma businessAbnorma = responseList.getEntity().get(0);
								BusinessAbnormaDto updateBADto = new BusinessAbnormaDto();
								updateBADto.setId(businessAbnorma.getId());
								updateBADto.setProcInstId(pid);
								updateBADto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
								updateBADto.setCheckDate(new Date());
								businessAbnormaServiceFacade.updateByPrimaryKey(updateBADto, true);
							}
						}

						// 添加流程审核需要的图片
						wsImageService.uploadAttachment(paramsSubscribeDto.getFileArr(),
								String.valueOf(subscribeDto.getId()), paramsSubscribeDto.getImageType(),
								subscribeDto.getProjectCode());

						// 修改房源状态为认筹
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						projectRoomDto.setId(subscribeDto.getRoomId());
						projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
						projectRoomServiceFacade.updateByPrimaryKey(projectRoomDto, true);

						// 不管需要不需要折扣审批,审核状态都为审核中
						SubscribeDto updateSubscribeDto = new SubscribeDto();
						updateSubscribeDto.setId(subscribeDto.getId());
						updateSubscribeDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
						updateSubscribeDto.setCheckDate(new Date());
						updateSubscribeDto.setProcInstId(pid);
						subscribeServiceFacade.updateByPrimaryKey(updateSubscribeDto, true);
						// 创建并发送提醒消息
						if (pid != null) {
							subscribeDto.setProcInstId(pid);
						}
					} else {
						// 添加流程审核需要的图片
						wsImageService.uploadAttachment(paramsSubscribeDto.getFileArr(),
								String.valueOf(subscribeDto.getId()), paramsSubscribeDto.getImageType(),
								subscribeDto.getProjectCode());
						resMsg = "认购保存成功";
					}
					ar.setObj(response.getEntity().getId());
					ar.setRes(Const.SUCCEED);
					ar.setResMsg(resMsg);
				} else {
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception ex) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "新增认购", params, JSONObject.toJSONString(ex));
				
				logger.error(ex.toString(), ex);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		// 操作失败,重置防重复提交Token
		if (Const.FAIL == ar.getRes()) {
			ar.setObj(newToken);
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		try {
			Response<Subscribe> response = subscribeServiceFacade.findById(id);
			if (response.isSuccess()) {
				ar.setSucceed(response.getEntity());
			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(SubscribeDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:subscribe:edit"))) {
			try {
				Response<Integer> response = subscribeServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:subscribe:delete"))) {
			try {
				Response<Integer> response = subscribeServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list")
	@ResponseBody
	public Page<SubscribeDto> list(SubscribeDto dto, Integer limit, Integer page) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:subscribe:list")) {
			try {
				dto = setQuerySubscribe(dto);
				Response<Page<SubscribeDto>> depositListResDto = subscribeService.getSubscribeList(dto, limit, page);
				if (depositListResDto.isSuccess()) {
					Page<SubscribeDto> pages = depositListResDto.getEntity();
					pages.setPageNumber(page);
					return pages;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<SubscribeDto>();
	}

	/**
	 * 
	 * subscribeExport:(导出客户信息). <br/>
	 * 
	 * @author Administrator
	 * @param value
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "subscribeExport")
	public void subscribeExport(String value, HttpServletResponse response, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		try {
			if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:subscribe:export"))) {
				String jsonStr = URLDecoder.decode(value, "utf-8");
				SubscribeDto dto = JSONObject.parseObject(jsonStr, SubscribeDto.class);
				dto.setIscustomerSub("1");
				dto = setQuerySubscribe(dto);
				String[] name = new String[] { "认购信息" }; // sheet信息
				List<String[]> headerList = new ArrayList<String[]>(); // 表头集合
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); // 数据集合
				// 设置表头字段
				String[] header = new String[] { "认购日期", "客户姓名", "房号", "户型", "计价面积(平方米)", "签约单价(元)", "合同金额(元)", "转签约日期",
						"是否逾期未转签约", "逾期天数", "认购金(元)", "已收认购金(元)", "经纪人", "业务状态", "审核状态" };
				headerList.add(header);
				List<SubscribeDto> subList = subscribeService.getSubscribeExportList(dto);
				List<Map<String, String>> listMap = subscribeService.returnFieldSubscribe(subList, header);
				list.add(listMap);
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SubscribeDto setQuerySubscribe(SubscribeDto dto) {
		if (dto.getDidTimeAfter() != null && !dto.getDidTimeAfter().equals("")) {
			dto.setDidTimeAfter(dto.getDidTimeAfter() + " 23:59:59");
		}
		if (dto.getDueTimeAfter() != null && !dto.getDueTimeAfter().equals("")) {
			dto.setDueTimeAfter(dto.getDueTimeAfter() + " 23:59:59");
		}
		if (dto.getCheckDateAfter() != null && !dto.getCheckDateAfter().equals("")) {
			dto.setCheckDateAfter(dto.getCheckDateAfter() + " 23:59:59");
		}
		dto.setOrders(" t.create_time desc ");
		User user = ShiroUtil.getCurrentUser();
		dto.setMerchantId(user.getMerchantId());
		dto.setPermissionUserId(user.getId());

		// 项目数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
		if (null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())) {
			dto.setResourcesCode(resourcesCode);
		} else if ("".equals(resourcesCode)) {
			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
		}
		return dto;
	}

	// 跳转退认购页面
	@RequestMapping(value = "toRetreat")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toRetreat(String subscribeId, ModelMap map) {
		map.put("subscribeId", subscribeId);
		Long projectId = subscribeServiceFacade.findById(new Long(subscribeId)).getEntity().getProjectId();
		map.put("specialFlow", projectServiceFacade.findById(projectId).getEntity().getSpecialFlow());
		return "/customer/subscribe/retreat";
	}

	// 加载退认购数据
	@RequestMapping(value = "loadRetreat")
	public @ResponseBody ExtResultVo loadRetreat(Long subscribeId, String businessAbnormaId) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(new JSONObject().toJSONString());
		JSONObject jsonObject = oaDataService.loadSubDelaySigned(subscribeId, businessAbnormaId);
		vo.setData(jsonObject.toJSONString());
		return vo;
	}

	// 保存退认购审批单
	@RequestMapping(value = "submitRetreat")
	@AvoidDuplicateSubmission(needRemoveToken = true)
	public @ResponseBody AjaxRes submitRetreat(Long subscribeId, String remark, String businessType, String fileUrlArr,
			String imageType, HttpServletRequest request, BigDecimal liquidat) {
		AjaxRes ar = getAjaxRes();
		// 操作失败时,重新刷新提交Token
		String newToken = TokenProcessor.getInstance().generateToken(request);
		request.getSession(false).setAttribute("token", newToken);
		Response<Subscribe> subscribeResponse = new Response<Subscribe>();
		User user = ShiroUtil.getCurrentUser();
		try {
			subscribeResponse = subscribeServiceFacade.findById(subscribeId);
			if (!subscribeResponse.isSuccess() || null == subscribeResponse.getEntity()) {
				ar.setFailMsg(Const.SAVE_FAIL);
				return ar;
			}

			Long projectId = subscribeResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}
			// 动态获取退认购审批流程KEY
			Project project = projectServiceFacade.findById(projectId).getEntity();
			ProcessTypeEnums params = null;
			if (project.getSpecialFlow() != null && project.getSpecialFlow().equals("1")) {
				params = ProcessTypeEnums.PROCESS_KEY_21;
			} else {
				params = ProcessTypeEnums.PROCESS_KEY_6;
			}
			String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId, params);
			if (StringUtils.isEmpty(startProcessKey)) {
				ar.setFailMsg("项目未设置退认购审批流程,请去项目流程菜单配置！");
				return ar;
			}
			// 检查流程节点是否已设置人员
			String processDefinitionKey = startProcessKey;
			boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
					processDefinitionKey);
			if (!isSeting) {
				ar.setFailMsg("退认购审批流程节点人员未设置");
				return ar;
			}
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setMerchantId(user.getMerchantId());
			businessAbnormaDto.setBusinessId(Long.valueOf(subscribeId));
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
			ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(businessAbnormaDto);
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				for (BusinessAbnorma ab : responseList.getEntity()) {
					if (ab.getAuditStatus().equals(AuditStatusEnum.AUDIT.getNo())
							|| ab.getAuditStatus().equals(AuditStatusEnum.TOSUBMIT.getNo())) {
						ar.setFailMsg("存在审批中的退认购记录，不能重复提交！");
						return ar;
					}
				}
			}
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(subscribeId);
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
			dto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			dto.setRemark(remark);
			dto.setMerchantId(user.getMerchantId());
			dto.setCreateUserId(user.getId());
			dto.setDelFlag("0");
			dto.setUpdateUserId(user.getId());
			dto.setUpdateTime(new Date());
			dto.setUserCode(user.getUserCode());
			dto.setAccessCode(subscribeResponse.getEntity().getAccessCode());
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
			if (response.isSuccess()) {
				// 启动流程
				Map<String, Object> variables = new HashMap<String, Object>();
				identityService.setAuthenticatedUserId(user.getUserAccount());
				String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
						processDefinitionKey, response.getEntity().getId().toString(), variables);
				// 更新审批状态
				BusinessAbnormaDto updateDto = new BusinessAbnormaDto();
				updateDto.setId(response.getEntity().getId());
				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setProcInstId(pid);
				updateDto.setCheckDate(new Date());
				businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
				// 保存流程附件
				if (StringUtils.isNotBlank(fileUrlArr)) {
					wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType,
							response.getEntity().getAccessCode());
				}
				// 更新认购没收违约金
				if ("1".equals(project.getSpecialFlow())) {
					SubscribeDto liquidatDto = new SubscribeDto();
					liquidatDto.setId(subscribeId);
					liquidatDto.setLiquidat(liquidat);
					subscribeServiceFacade.updateByPrimaryKey(liquidatDto, true);
				}
				ar.setSucceed(response.getEntity().getId().toString());

			} else {
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		} catch (Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "新增退认购", JSONObject.toJSONString(subscribeResponse), JSONObject.toJSONString(ex));
			
			logger.error("退认购错误", ex);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		// 操作失败,重置防重复提交Token
		if (Const.FAIL == ar.getRes()) {
			ar.setObj(newToken);
		}
		return ar;
	}

	// 跳转退认购详情页
	@RequestMapping(value = "toRetreatView")
	public String toRetreatView(String id, ModelMap map, String processFlag, HttpServletRequest request) {
		Response<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade.findById(Long.valueOf(id));
		map.put("subscribeId", businessAbnormaResponse.getEntity().getBusinessId());
		map.put("businessAbnormaId", id);
		map.put("processFlag", processFlag);
		map.put("auditStatus", businessAbnormaResponse.getEntity().getAuditStatus());
		map.put("procInstId", businessAbnormaResponse.getEntity().getProcInstId());
		map.put("back", request.getParameter("back"));
		Long projectId = subscribeServiceFacade.findById(new Long(businessAbnormaResponse.getEntity().getBusinessId())).getEntity().getProjectId();
		map.put("specialFlow", projectServiceFacade.findById(projectId).getEntity().getSpecialFlow());
		return "/customer/subscribe/retreatView";
	}

	// 跳转延期签约页面
	@RequestMapping(value = "toDelaySigned")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toDelaySigned(String subscribeId, ModelMap map) {
		map.put("subscribeId", subscribeId);
		boolean showGrid = showHisAuditGrid(Long.valueOf(subscribeId));
		map.put("showGrid", showGrid);

		return "/customer/subscribe/delaySinged";
	}

	// 保存延期签约批单
	@AvoidDuplicateSubmission(needRemoveToken = true)
	@RequestMapping(value = "submitDelaySinged")
	public @ResponseBody AjaxRes submitDelaySinged(Long subscribeId, String remark, String delayDate, String fileUrlArr,
			String imageType, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		// 操作失败时,重新刷新提交Token
		String newToken = TokenProcessor.getInstance().generateToken(request);
		request.getSession(false).setAttribute("token", newToken);
		User user = ShiroUtil.getCurrentUser();
		Response<Subscribe> subscribeResponse = new Response<Subscribe>();
		try {
			subscribeResponse = subscribeServiceFacade.findById(subscribeId);
			if (!subscribeResponse.isSuccess() || null == subscribeResponse.getEntity()) {
				ar.setFailMsg(Const.SAVE_FAIL);
				return ar;
			}
			Long projectId = subscribeResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}
			// 是否存在审核中的延期签约记录，如果存在，则不能再次发起
			BusinessAbnormaDto queryDto = new BusinessAbnormaDto();
			queryDto.setBusinessId(subscribeId);
			queryDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_9.getNo());
			ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(queryDto);
			boolean isSubmit = true;
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				List<BusinessAbnorma> abList = responseList.getEntity();
				for (BusinessAbnorma ab : abList) {
					String auditStatus = ab.getAuditStatus();
					if (auditStatus.equals(AuditStatusEnum.AUDIT.getNo())
							|| auditStatus.equals(AuditStatusEnum.TOSUBMIT.getNo())) {
						isSubmit = false;
						break;
					}
				}
			}
			if (!isSubmit) {
				ar.setFailMsg("存在审核中延期签约记录，不能重复发起");
				return ar;
			}

			Date conversionSignDate = subscribeResponse.getEntity().getConversionSignDate();
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(subscribeId);
			dto.setDelaydate(com.emm.yixun.common.utils.DateUtils.StringToDate(delayDate, DateStyle.YYYY_MM_DD));
			dto.setConversionSignDate(conversionSignDate);
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_9.getNo());
			dto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			dto.setRemark(remark);
			dto.setMerchantId(user.getMerchantId());
			dto.setCreateUserId(user.getId());
			dto.setDelFlag("0");
			dto.setUpdateUserId(user.getId());
			dto.setUpdateTime(new Date());
			dto.setUserCode(user.getUserCode());
			dto.setAccessCode(subscribeResponse.getEntity().getAccessCode());
			Long delayDays = com.emm.yixun.common.utils.DateUtils.getDaysSub(conversionSignDate, dto.getDelaydate());
			if (delayDays <= 0) {
				ar.setFailMsg("延期签约日期不能在认购转签约日期之前");
				return ar;
			}
			String processDefinitionKey = "";
			// 判断商户是绿城还是丰策
			if (MerchantEnum.FENGCE.getNo().equals(String.valueOf(user.getMerchantId()))) {
				String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
						ProcessTypeEnums.PROCESS_KEY_9);
				if (StringUtils.isEmpty(startProcessKey)) {
					ar.setFailMsg("项目未设置延期签约审批流程,请去项目流程菜单配置！");
					return ar;
				}
				processDefinitionKey = startProcessKey;
			} else {
				if (0 < delayDays && delayDays <= 15) {
					String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
							ProcessTypeEnums.PROCESS_KEY_9);
					if (StringUtils.isEmpty(startProcessKey)) {
						ar.setFailMsg("项目未设置延期签约审批流程,请去项目流程菜单配置！");
						return ar;
					}
					processDefinitionKey = startProcessKey;
				} else if (15 < delayDays && delayDays <= 30) {
					String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
							ProcessTypeEnums.PROCESS_KEY_10);
					if (StringUtils.isEmpty(startProcessKey)) {
						ar.setFailMsg("项目未设置延期签约审批流程,请去项目流程菜单配置！");
						return ar;
					}
					processDefinitionKey = startProcessKey;
				} else if (delayDays > 30) {
					String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
							ProcessTypeEnums.PROCESS_KEY_11);
					if (StringUtils.isEmpty(startProcessKey)) {
						ar.setFailMsg("项目未设置延期签约审批流程,请去项目流程菜单配置！");
						return ar;
					}
					processDefinitionKey = startProcessKey;
				}
			}

			boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId,
					processDefinitionKey);
			if (!isSeting) {
				ar.setFailMsg("延期签约审批流程节点人员未设置");
				return ar;
			}
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
			if (response.isSuccess()) {
				// 启动流程
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("subDelaySignedDays", delayDays);

				identityService.setAuthenticatedUserId(user.getUserAccount());
				String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
						processDefinitionKey, response.getEntity().getId().toString(), variables);
				// 更新审批状态
				BusinessAbnormaDto updateDto = new BusinessAbnormaDto();
				updateDto.setId(response.getEntity().getId());
				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setProcInstId(pid);
				updateDto.setCheckDate(new Date());
				businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
				// 保存流程附件
				if (StringUtils.isNotBlank(fileUrlArr)) {
					wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType,
							response.getEntity().getAccessCode());
				}
				ar.setSucceed(response.getEntity().getId());

			} else {
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		} catch (Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "新增认购延期签约", JSONObject.toJSONString(subscribeResponse), JSONObject.toJSONString(ex));
			
			logger.error("认购延期签约", ex);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		// 操作失败,重置防重复提交Token
		if (Const.FAIL == ar.getRes()) {
			ar.setObj(newToken);
		}
		return ar;
	}

	// 跳转退认购详情页
	@RequestMapping(value = "toDelaySignedView")
	public String toDelaySignedView(String id, String processFlag, ModelMap map) {
		Response<BusinessAbnorma> businessAbnormaResponse = businessAbnormaServiceFacade.findById(Long.valueOf(id));
		map.put("subscribeId", businessAbnormaResponse.getEntity().getBusinessId());
		map.put("businessAbnormaId", id);
		map.put("processFlag", processFlag != null ? processFlag : "false");
		map.put("auditStatus", businessAbnormaResponse.getEntity().getAuditStatus());
		map.put("procInstId", businessAbnormaResponse.getEntity().getProcInstId());

		boolean showGrid = showHisAuditGrid(businessAbnormaResponse.getEntity().getBusinessId());
		map.put("showGrid", showGrid);

		return "/customer/subscribe/delaySingedView";
	}

	@RequestMapping(value = "toChangeName")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toChangeName(String subscribeId, ModelMap map) {
		map.put("subscribeId", subscribeId);
		Response<Subscribe> subscribeResponse = subscribeServiceFacade.findById(Long.valueOf(subscribeId));
		if (subscribeResponse.isSuccess() && null != subscribeResponse.getEntity()) {
			map.put("projectId", subscribeResponse.getEntity().getProjectId());
		}
		User user = ShiroUtil.getCurrentUser();
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		bcvDto.setProjectId(subscribeResponse.getEntity().getProjectId());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		map.put("documentType", dtArray.toJSONString());
		return "/customer/subscribe/changeName";
	}

	// 提交认购更名申请
	@RequestMapping(value = "submitChangeName")
	@AvoidDuplicateSubmission(needRemoveToken = true)
	public @ResponseBody AjaxRes submitChangeName(String params, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		// 操作失败时,重新刷新提交Token
		String newToken = TokenProcessor.getInstance().generateToken(request);
		request.getSession(false).setAttribute("token", newToken);
		User user = ShiroUtil.getCurrentUser();
		try {
			JSONObject paramsJson = JSON.parseObject(params);
			Long subscribeId = paramsJson.getLong("subscribeId");
			String remark = paramsJson.getString("remark");
			Response<Subscribe> subscribeResponse = subscribeServiceFacade.findById(subscribeId);
			if (!subscribeResponse.isSuccess() || null == subscribeResponse.getEntity()) {
				ar.setFailMsg(Const.SAVE_FAIL);
				return ar;
			}
			// 是否存在审核中的延期签约记录，如果存在，则不能再次发起
			BusinessAbnormaDto queryDto = new BusinessAbnormaDto();
			queryDto.setBusinessId(subscribeId);
			queryDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_11.getNo());
			ResponseList<BusinessAbnorma> responseList = businessAbnormaServiceFacade.findByDto(queryDto);
			boolean isSubmit = true;
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				List<BusinessAbnorma> abList = responseList.getEntity();
				for (BusinessAbnorma ab : abList) {
					String auditStatus = ab.getAuditStatus();
					if (auditStatus.equals(AuditStatusEnum.AUDIT.getNo())
							|| auditStatus.equals(AuditStatusEnum.TOSUBMIT.getNo())) {
						isSubmit = false;
						break;
					}
				}
			}
			if (!isSubmit) {
				ar.setFailMsg("存在审核中更名记录，不能再次发起");
				return ar;
			}
			Long projectId = subscribeResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}

			// 动态获取价格方案流程KEY
			String startProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
					ProcessTypeEnums.PROCESS_KEY_8);
			if (StringUtils.isEmpty(startProcessKey)) {
				ar.setFailMsg("项目未设置认购更名审批流程,请去项目流程菜单配置！");
				return ar;
			}
			// 检查流程节点是否已设置人员
			String processKey = startProcessKey;
			boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId, processKey);
			if (!isSeting) {
				ar.setFailMsg("认购更名节点人员未设置");
				return ar;
			}
			Subscribe subscribe = subscribeResponse.getEntity();
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(subscribeId);
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_11.getNo());
			dto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			dto.setRemark(remark);
			dto.setMerchantId(user.getMerchantId());
			dto.setCreateUserId(user.getId());
			dto.setDelFlag("0");
			dto.setUpdateUserId(user.getId());
			dto.setUpdateTime(new Date());
			dto.setUserCode(user.getUserCode());
			dto.setAccessCode(subscribeResponse.getEntity().getAccessCode());
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
			if (response.isSuccess()) {
				// 保存更名信息
				JSONArray familyMembers = paramsJson.getJSONArray("familyMember");
				// 新客户信息
				JSONArray newFamilyMembers = paramsJson.getJSONArray("newFamilyMember");
				// 保存新共同购房者信息
				if (familyMembers.size() > 0) {
					ar = getAr(ar, familyMembers, subscribe, response, user, MemberTypeEnum.SUBSCRIBECHANGENAME.getNo(),
							null);
					if (ar.getRes() == 0) {
						return ar;
					}
				}
				// 保存新客户信息
				if (newFamilyMembers.size() > 0) {
					ar = getAr(ar, newFamilyMembers, subscribe, response, user, MemberTypeEnum.N_CUSTOMER_INFO.getNo(),
							null);
					if (ar.getRes() == 0) {
						return ar;
					}
				}

				// 保存原客户信息
				Response<SubscribeDto> response2 = subscribeServiceFacade.selectSubscribeCustomer(subscribeId);
				if (response2.isSuccess() && response2.getEntity() != null) {
					JSONArray yFamilyMember = new JSONArray();
					FamilyMemberDto dto2 = new FamilyMemberDto();
					dto2.setDocumentType(response2.getEntity().getDtype());
					dto2.setDocumentNumber(response2.getEntity().getDocumentNumber());
					dto2.setMobile(response2.getEntity().getMobile());
					dto2.setMemberName(response2.getEntity().getMemberName());
					yFamilyMember.add(JSON.toJSONString(dto2));
					ar = getAr(ar, yFamilyMember, subscribe, response, user, MemberTypeEnum.Y_CUSTOMER_INFO.getNo(),
							response2.getEntity().getCustomerId());
					if (ar.getRes() == 0) {
						return ar;
					}
				}
				// 保存原共同购房者信息
				FamilyMemberDto fmd = new FamilyMemberDto();
				fmd.setMemberType("3");
				fmd.setBuyId(subscribeId);
				ResponseList<FamilyMember> response3 = familyMemberServiceFacade.findByDto(fmd);
				if (response3.isSuccess() && response3.getEntity() != null && response3.getEntity().size() > 0) {
					for (FamilyMember familyMember : response3.getEntity()) {
						FamilyMemberDto memberDto = new FamilyMemberDto();
						BeanUtil.convert2T(memberDto, familyMember);
						memberDto.setBuyId(response.getEntity().getId());
						memberDto.setMemberType(MemberTypeEnum.Y_COMMON_INFO.getNo());
						Response<FamilyMemberDto> familyMemberDtoResponse = familyMemberServiceFacade.save(memberDto);
						if (!familyMemberDtoResponse.isSuccess()) {
							ar.setFailMsg(Const.SAVE_FAIL);
							break;
						}
					}
				}
				Map<String, Object> variables = new HashMap<String, Object>();
				// 启动流程
				identityService.setAuthenticatedUserId(user.getUserAccount());
				String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId, processKey,
						response.getEntity().getId().toString(), variables);
				// 更新审批状态
				BusinessAbnormaDto updateDto = new BusinessAbnormaDto();
				updateDto.setId(response.getEntity().getId());
				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setProcInstId(pid);
				updateDto.setCheckDate(new Date());
				businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);

				// 保存流程文件
				String fileUrlArr = paramsJson.getString("fileUrlArr");
				String imageType = paramsJson.getString("imageType");
				if (StringUtils.isNotBlank(fileUrlArr)) {
					wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType,
							subscribeResponse.getEntity().getAccessCode());
				}

				ar.setSucceed(response.getEntity().getId());
			} else {
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		} catch (Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "新增认购更名", params, JSONObject.toJSONString(ex));
			
			logger.error("新增认购更名", ex);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		// 操作失败,重置防重复提交Token
		if (Const.FAIL == ar.getRes()) {
			ar.setObj(newToken);
		}
		return ar;
	}

	private AjaxRes getAr(AjaxRes ar, JSONArray familyMembers, Subscribe subscribe,
			Response<BusinessAbnormaDto> response, User user, String no, Long customerId) {
		if (null != familyMembers && familyMembers.size() > 0) {
			for (int i = 0; i < familyMembers.size(); i++) {
				String familyMemberStr = (String) familyMembers.get(i);
				FamilyMemberDto familyMemberRow = JSONObject.parseObject(familyMemberStr, FamilyMemberDto.class);
				if (customerId != null) {
					familyMemberRow.setCustomerId(customerId);
				} else {
					familyMemberRow.setCustomerId(subscribe.getCustomerId());
				}
				familyMemberRow.setBuyId(response.getEntity().getId());
				familyMemberRow.setProjectId(subscribe.getProjectId());
				familyMemberRow.setProjectCode(subscribe.getProjectCode());
				familyMemberRow.setMemberType(no);
				familyMemberRow.setAccessCode(subscribe.getAccessCode());
				familyMemberRow.setUserCode(user.getUserCode());
				familyMemberRow.setMerchantId(user.getMerchantId());
				familyMemberRow.setCreateUserId(user.getId());
				familyMemberRow.setDelFlag("0");
				familyMemberRow.setUpdateUserId(user.getId());
				familyMemberRow.setUpdateTime(new Date());
				familyMemberRow.setIsDefault("0");
				familyMemberRow.setSex("3");
				Response<FamilyMemberDto> familyMemberDtoResponse = familyMemberServiceFacade.save(familyMemberRow);
				if (!familyMemberDtoResponse.isSuccess()) {
					ar.setFailMsg(Const.SAVE_FAIL);
				} else {
					ar.setRes(Const.SUCCEED);
				}
			}
		}
		return ar;
	}

	// 加载退房/合同变更表单数据
	@RequestMapping(value = "loadSubscribeInfo")
	public @ResponseBody ExtResultVo loadSubscribeInfo(Long subscribeId, String businessAbnormaId) {
		ExtResultVo vo = new ExtResultVo();
		vo.setSuccess(true);
		vo.setData(new JSONObject().toJSONString());
		JSONObject jsonObject = oaDataService.loadSubChangeNameInfo(subscribeId, businessAbnormaId);
		vo.setData(jsonObject.toJSONString());
		return vo;
	}

	// 查看
	@RequestMapping(value = "toDelaySignedIS", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes toDelaySignedIS(Long subscribeId) {
		AjaxRes ar = getAjaxRes();
		ar.setRes(Const.SUCCEED);
		ar.setResMsg("0");
		try {
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(subscribeId);
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_9.getNo());
			// 审核条件去掉,根据状态判断
			// 1、待提交: 无暂存功能,不存在待提交延期签约审批
			// 2、审核中: 存在未审核完成记录,不允许发起
			// 3、已退回: 退回后,无法再次发起
			// 4、已通过: 已通过,再次提醒是否需要再次发起
			businessAbnormaDto.setOrders("create_time desc");
			ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade.findByDto(businessAbnormaDto);
			if (businessAbnormas.isSuccess() && null != businessAbnormas.getEntity()
					&& businessAbnormas.getEntity().size() != 0) {
				List<BusinessAbnorma> baList = businessAbnormas.getEntity();
				BusinessAbnorma ba = baList.get(0);
				String auditStatus = ba.getAuditStatus();
				if (AuditStatusEnum.AUDIT.getNo().equals(auditStatus)) {
					// 存在审核中延期审核,返回值定义为1
					ar.setResMsg("1");
				} else if (AuditStatusEnum.SUCCESS.getNo().equals(auditStatus)
						|| AuditStatusEnum.REJECT.getNo().equals(auditStatus)) {
					// 存在已通过延期审核,返回值定义为2
					ar.setResMsg("2");
					ar.setObj(DateUtils.DateToString(ba.getCheckDate(), "yyyy年MM月dd日"));
				}
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setRes(Const.FAIL);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	/**
	 * 客户信息 功能描述: <br>
	 * 〈功能详细描述〉
	 * 
	 * @param subscribeId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping(value = "selectSubscribeCustomer", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes selectSubscribeCustomer(Long subscribeId) {
		AjaxRes ar = getAjaxRes();
		try {
			Response<SubscribeDto> response = subscribeServiceFacade.selectSubscribeCustomer(subscribeId);
			if (response.isSuccess() && response.getEntity() != null) {
				ar.setSucceed(response.getEntity());
			} else {
				ar.setRes(Const.FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setRes(10000);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "toEdit")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public String toEdit(ModelMap map, Long id, String processFlag, HttpServletRequest request, String returnUrl) {
		/* if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){ */
		// 查询菜单按钮权限

		User user = ShiroUtil.getCurrentUser();
		// 认筹开关,默认未关闭(false) ,true已关闭
		boolean payDepositOff = false;
		Response<Boolean> response4 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
		if (response4.isSuccess()) {
			payDepositOff = response4.getEntity();
		}
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		Response<SubscribeInfo> response = subscribeServiceFacade.findByIdInfo(id);
		if (response.isSuccess()) {
			HashMap<String, Double> maps = signedServiceFacade.signedContractAmount(null, id);
			SubscribeInfo subscribe = response.getEntity();
			String customerId = String.valueOf(subscribe.getCustomerId());
			String roomId = String.valueOf(subscribe.getRoomId());
			map.put("subscribe", JSONObject.toJSONString(subscribe));
			map.put("customerId", StringUtils.isBlank(customerId) ? "" : customerId);
			map.put("roomId", StringUtils.isBlank(roomId) ? "" : roomId);
			if (subscribe.getDiscountApproval().equals("1")) {
				// 折扣审批编号 认购
				BusinessAbnormaDto bus = new BusinessAbnormaDto();
				bus.setBusinessId(subscribe.getId());
				bus.setBusinessType("0");
				ResponseList<BusinessAbnorma> responseListBus = businessAbnormaServiceFacade.findByDto(bus);
				if (responseListBus.isSuccess() && responseListBus.getEntity() != null
						&& responseListBus.getEntity().size() > 0) {
					map.put("busProcInstId", responseListBus.getEntity().get(0).getProcInstId());
					map.put("busAutoStatus", responseListBus.getEntity().get(0).getAuditStatus());
				}

			}
			subscribe.setReceivedPayAmount(haveAmountById(id));
			if (subscribe.getConversionSignDate() != null) {
				Date newConversionDate = com.emm.yixun.common.utils.DateUtils.addDay(subscribe.getConversionSignDate(),
						1);
				if (new Date().getTime() > newConversionDate.getTime()) {
					map.put("yanqiStatus", "0");
				} else {
					map.put("yanqiStatus", "1");
				}
			} else {
				map.put("yanqiStatus", "0");
			}
			map.put("procInstId", subscribe.getProcInstId());
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setReceivablesType("1");// 认购
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			// haveReceiveRefundDto.setStatus("0");// 已结清
			ResponseList<HaveReceiveRefund> response3 = haveReceiveRefundServiceFacade.findByDto(haveReceiveRefundDto);
			if (response3.isSuccess()) {
				List<HaveReceiveRefund> haveReceiveRefunds = response3.getEntity();
				if (haveReceiveRefunds != null && haveReceiveRefunds.size() != 0) {
					BigDecimal total = new BigDecimal("0.00");
					for (HaveReceiveRefund refund : haveReceiveRefunds) {
						if (!refund.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
							map.put("amountDetail", "1");
							total = total.add(refund.getRealAmount());
						}
					}
					if (total.compareTo(subscribe.getDepositReceivable()) == 0) {
						map.put("shouStatus", "1");
					} else {
						map.put("shouStatus", "0");
					}
				} else {
					if (subscribe.getDepositReceivable().compareTo(new BigDecimal("0")) == 0
							|| subscribe.getDepositReceivable() == null) {
						map.put("shouStatus", "1");
					} else {
						map.put("shouStatus", "0");
					}

				}
			} else {
				map.put("shouStatus", "0");
			}
			Response<ProjectRoom> response2 = projectRoomServiceFacade.findById(subscribe.getRoomId());
			if (response2.isSuccess()) {
				ProjectRoom projectRoom = response2.getEntity();
				map.put("roomStatus", projectRoom.getRoomStatus());
			}
			map.put("auditStatus", subscribe.getAuditStatus());
			if (subscribe.getBusinessStatus().equals("5")) {
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
				businessAbnormaDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					map.put("businessAbnormaId", businessAbnormas.getEntity().get(0).getId());
					map.put("huanStatus", "1");
				} else {
					map.put("huanStatus", "0");
				}

			} else if (!subscribe.getBusinessStatus().equals("3")) {
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
				// businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					BusinessAbnorma abnorma = businessAbnormas.getEntity().get(0);
					if (abnorma.getAuditStatus().equals("1")) {// 待提交隐藏
						map.put("huanStatus", "1");
					} else if (abnorma.getAuditStatus().equals("2")) {// 已退回显示
						map.put("huanStatus", "0");
					}
					map.put("businessStatus", subscribe.getBusinessStatus());
				} else {
					businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_8.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					ResponseList<BusinessAbnorma> businessAbnormas2 = businessAbnormaServiceFacade
							.findByDto(businessAbnormaDto);
					if (businessAbnormas2.isSuccess() && businessAbnormas2.getEntity() != null
							&& businessAbnormas2.getEntity().size() != 0) {
						map.put("businessAbnormaId", businessAbnormas2.getEntity().get(0).getId());
						map.put("huanStatus", "1");
						map.put("businessStatus", "5");
					} else {
						map.put("huanStatus", "0");
						map.put("businessStatus", subscribe.getBusinessStatus());
					}
				}
			} else {// 已通过隐藏
				BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_1.getNo());
				businessAbnormaDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade
						.findByDto(businessAbnormaDto);
				if (businessAbnormas.isSuccess() && businessAbnormas.getEntity() != null
						&& businessAbnormas.getEntity().size() != 0) {
					map.put("businessAbnormaId", businessAbnormas.getEntity().get(0).getId());
					map.put("huanStatus", "1");
				} else {
					map.put("huanStatus", "0");
				}
				map.put("businessStatus", subscribe.getBusinessStatus());
			}
			String subscribeStr = JSON.toJSONString(subscribe);
			Double payAepositAmount = maps.get("payAepositAmount");
			Double subscribeAmount = maps.get("subscribeAmount") - payAepositAmount;
			JSONObject object = JSONObject.parseObject(subscribeStr);
			object.put("alsubscribeAmount", subscribeAmount);
			subscribeStr = JSON.toJSONString(object);
			map.put("businessStatus", subscribe.getBusinessStatus());
			map.put("subscribeRecord", subscribeStr);
			JSONObject estateRecord = oaDataService.getEstateRecord(subscribe.getRoomId());
			estateRecord.put("calculateArea", subscribe.getCalculateArea());
			estateRecord.put("unitPrice", subscribe.getConversionPrice());
			estateRecord.put("totalPrice", subscribe.getLumpsumPrice());
			map.put("estateRecord", estateRecord.toJSONString());
			JSONObject customerRecord = oaDataService.getCustomerRecord(subscribe.getCustomerId());
			map.put("customerRecord", customerRecord.toJSONString());
			map.put("userName", subscribe.getUserName());
		}
		map.put("documentType", dtArray.toJSONString());
		map.put("processFlag", processFlag != null ? processFlag : "false");
		map.put("subscribeId", id);
		map.put("permitBtn", getPermissionBtnArray());
		map.put("menu", request.getParameter("menu"));
		map.put("payDepositOff", payDepositOff);
		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			map.put("returnBackParam", returnUrl);
		}
		Boolean showChooseCustomer = Boolean.FALSE;
		map.put("showChooseCustomer", showChooseCustomer);

		return "/customer/subscribe/edit";
		/*
		 * } return Const.NO_AUTHORIZED_URL;
		 */
	}

	public boolean subDiscountFlowCheck(User user) {
		boolean flag = true;
		Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
		if (merchantResponse.isSuccess() && merchantResponse.getEntity() != null) {
			String information = merchantResponse.getEntity().getPhoneInformation();
			com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = jsonObject.getString("type");
				String status = jsonObject.getString("status");
				if ("7".equals(type) && "0".equals(status)) {
					flag = false;
				}
			}
		}
		return flag;
	}

	/**
	 * 判断是否显示同房同流程的其他审批记录
	 * 
	 * @param businessId
	 * @return
	 */
	public boolean showHisAuditGrid(long businessId) {
		boolean showGrid = false;
		BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
		businessAbnormaDto.setBusinessId(businessId);
		businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_9.getNo());
		businessAbnormaDto.setOrders("create_time desc");
		ResponseList<BusinessAbnorma> businessAbnormas = businessAbnormaServiceFacade.findByDto(businessAbnormaDto);
		if (businessAbnormas.isSuccess() && null != businessAbnormas.getEntity()
				&& businessAbnormas.getEntity().size() != 0) {
			List<BusinessAbnorma> baList = businessAbnormas.getEntity();
			// 存在延期记录,并且只有一条时,判断是否已结束..审核中的不显示
			if (baList.size() > 0 && baList.size() == 1) {
				BusinessAbnorma ba = baList.get(0);
				String auditStatus = ba.getAuditStatus();
				if (AuditStatusEnum.SUCCESS.getNo().equals(auditStatus)
						|| AuditStatusEnum.REJECT.getNo().equals(auditStatus)) {
					showGrid = true;
				}
			} else {
				// 超过1条的,直接显示全部历史
				showGrid = true;
			}
		}
		return showGrid;
	}

}
